﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using VideoSDK;
using PlayerSDK;

namespace TestVideoDecode
{
    public partial class Form1 : Form
    {
        VideoSDKHC video = new VideoSDKHC();
        PlayerSDKHC player = new PlayerSDKHC();
        Bitmap decodeImage = null;
        public Form1()
        {
            InitializeComponent();

            this.video.RealStreamCallback = new IVideo.RealStreamCallback(player.Open);

            this.player.DecodeCallback = new IPlayer.DecodeCallback(DecodeCall);
        }

        void DecodeCall(IntPtr buffer, int width, int height)
        {
            if (this.decodeImage == null) 
                decodeImage = new Bitmap(width, height);

            ImageProcessing.YV12.DecodeYV12ToRGB(buffer, decodeImage);

            this.pBDecode.Invalidate();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!video.LoginEncoder("192.168.1.188", 8000, "admin", "12345"))
                MessageBox.Show("User Login Failed!");
        }

        protected override void OnClosed(EventArgs e)
        {
            if (this.video.IsLogined)
                this.video.LogoutEncoder();

            if (this.video.IsOpened)
                this.video.CloseVideo();

            if (this.decodeImage != null)
                this.decodeImage.Dispose();

            base.OnClosed(e);
        }

        private void bOpen_Click(object sender, EventArgs e)
        {
            if (this.video.IsLogined && !this.video.IsOpened)
            {
                if (!this.video.OpenVideo(1, this.pBVideo.Handle))
                    MessageBox.Show("Open Video Failed!");
            }
        }

        private void pBDecode_Paint(object sender, PaintEventArgs e)
        {
            if (this.decodeImage == null) return;

            lock (this.decodeImage)
            {
                e.Graphics.DrawImage(this.decodeImage, new Rectangle(new Point(), pBDecode.Size));
            }
        }
    }
}
